/**
 * Module dependencies.
 */

var express = require('express');
var bodyParser = require('body-parser');
var router = require('./router');
var db = require('./mongodb');
var config = require('config-lite');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var connectMongo = require('connect-mongo');
var app = express();

// all environments

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,PATCH,OPTIONS");
    if (req.method === 'OPTIONS') {
        res.statusCode = 200;
        res.end();
    } else {
        next();
    }
});

const MongoStore = connectMongo(session);
app.use(cookieParser());
app.use(session({
    name: config.session.name,
    secret: config.session.secret,
    resave: true,
    saveUninitialized: false,
    cookie: config.session.cookie,
    store: new MongoStore({
        url: config.url
    })
}))

app.use(bodyParser.json());//使用bodyparser并配置其参数
app.use(bodyParser.urlencoded({ extended: false }));//使用bodyparser并配置其参数
app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.status(500).send('Something broke!');
});
router(app);

app.listen(config.port, () => {
    console.log(`成功监听端口：${config.port}`)
});